package com.itany.corejava.day17;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServerC {

    public static void main(String[] args) {
        ServerSocket ss=null;
        try{

            ss=new ServerSocket(8888);

            while(true){
                Socket s=null;

                try{

                    System.out.println("++++++");
                    s=ss.accept();

                    new MyThread(s).start();

                    System.out.println("------");

                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class MyThread extends Thread{
        private Socket s;

        public MyThread(Socket s) {
            this.s = s;
        }

        @Override
        public void run() {

            BufferedReader br=null;

            PrintWriter pw=null;

            try{
                br=new BufferedReader(
                        new InputStreamReader(
                                s.getInputStream()
                        )
                );

                String name=br.readLine();

                if("abc".equals(name)) {
                    Thread.sleep(999999);
                }

                pw=new PrintWriter(s.getOutputStream());

                pw.println("Hello "+name);

                pw.flush();
            }catch (Exception e){
                e.printStackTrace();
            }finally{
                if(br!=null){
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(pw!=null){
                    pw.close();
                }
                if(s!=null){
                    try {
                        s.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
